// 游戏常量
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
const TANK_SIZE = 30;
const BULLET_SIZE = 5;
const TANK_SPEED = 3;
const BULLET_SPEED = 5;
const ENEMY_COUNT = 5;
const ENEMY_SPAWN_INTERVAL = 5000;

// 游戏类
class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.canvas.width = CANVAS_WIDTH;
        this.canvas.height = CANVAS_HEIGHT;
        
        this.player = new Tank(CANVAS_WIDTH / 2, CANVAS_HEIGHT - 50, 'player');
        this.enemies = [];
        this.bullets = [];
        this.score = 0;
        
        this.setupEventListeners();
        this.spawnEnemies();
        this.gameLoop();
    }

    setupEventListeners() {
        window.addEventListener('keydown', (e) => {
            switch(e.key.toLowerCase()) {
                case 'w': this.player.moving.up = true; break;
                case 's': this.player.moving.down = true; break;
                case 'a': this.player.moving.left = true; break;
                case 'd': this.player.moving.right = true; break;
                case ' ': this.player.shoot(this.bullets); break;
            }
        });

        window.addEventListener('keyup', (e) => {
            switch(e.key.toLowerCase()) {
                case 'w': this.player.moving.up = false; break;
                case 's': this.player.moving.down = false; break;
                case 'a': this.player.moving.left = false; break;
                case 'd': this.player.moving.right = false; break;
            }
        });
    }

    spawnEnemies() {
        while (this.enemies.length < ENEMY_COUNT) {
            const x = Math.random() * (CANVAS_WIDTH - TANK_SIZE);
            const y = Math.random() * (CANVAS_HEIGHT / 2);
            this.enemies.push(new Tank(x, y, 'enemy'));
        }
        setTimeout(() => this.spawnEnemies(), ENEMY_SPAWN_INTERVAL);
    }

    update() {
        // 更新玩家
        this.player.update();
        this.player.keepInBounds(CANVAS_WIDTH, CANVAS_HEIGHT);

        // 更新敌人
        this.enemies.forEach(enemy => {
            enemy.update();
            enemy.keepInBounds(CANVAS_WIDTH, CANVAS_HEIGHT);
            enemy.ai(this.player, this.bullets);
        });

        // 更新子弹
        this.bullets = this.bullets.filter(bullet => {
            bullet.update();
            return bullet.isActive(CANVAS_WIDTH, CANVAS_HEIGHT);
        });

        // 碰撞检测
        this.checkCollisions();
    }

    checkCollisions() {
        // 子弹与坦克的碰撞检测
        this.bullets.forEach(bullet => {
            if (bullet.fromPlayer) {
                this.enemies.forEach((enemy, index) => {
                    if (this.checkCollision(bullet, enemy)) {
                        enemy.health -= 25;
                        bullet.active = false;
                        if (enemy.health <= 0) {
                            this.enemies.splice(index, 1);
                            this.score += 100;
                            document.getElementById('score').textContent = this.score;
                        }
                    }
                });
            } else {
                if (this.checkCollision(bullet, this.player)) {
                    this.player.health -= 10;
                    bullet.active = false;
                    document.getElementById('health').textContent = this.player.health;
                    if (this.player.health <= 0) {
                        alert('游戏结束！得分：' + this.score);
                        location.reload();
                    }
                }
            }
        });
    }

    checkCollision(bullet, tank) {
        return bullet.x > tank.x && 
               bullet.x < tank.x + TANK_SIZE &&
               bullet.y > tank.y && 
               bullet.y < tank.y + TANK_SIZE;
    }

    draw() {
        this.ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        
        // 绘制玩家
        this.player.draw(this.ctx);
        
        // 绘制敌人
        this.enemies.forEach(enemy => enemy.draw(this.ctx));
        
        // 绘制子弹
        this.bullets.forEach(bullet => bullet.draw(this.ctx));
    }

    gameLoop() {
        this.update();
        this.draw();
        requestAnimationFrame(() => this.gameLoop());
    }
}

// 坦克类
class Tank {
    constructor(x, y, type) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.health = 100;
        this.moving = {
            up: false,
            down: false,
            left: false,
            right: false
        };
        this.lastShot = 0;
    }

    update() {
        if (this.moving.up) this.y -= TANK_SPEED;
        if (this.moving.down) this.y += TANK_SPEED;
        if (this.moving.left) this.x -= TANK_SPEED;
        if (this.moving.right) this.x += TANK_SPEED;
    }

    keepInBounds(width, height) {
        this.x = Math.max(0, Math.min(width - TANK_SIZE, this.x));
        this.y = Math.max(0, Math.min(height - TANK_SIZE, this.y));
    }

    shoot(bullets) {
        const now = Date.now();
        if (now - this.lastShot > 500) {  // 射击冷却时间
            bullets.push(new Bullet(
                this.x + TANK_SIZE / 2,
                this.y + (this.type === 'player' ? 0 : TANK_SIZE),
                this.type === 'player'
            ));
            this.lastShot = now;
        }
    }

    ai(player, bullets) {
        if (this.type !== 'enemy') return;

        // 移动AI
        const dx = player.x - this.x;
        const dy = player.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 躲避玩家子弹
        const nearestBullet = bullets.find(b => b.fromPlayer && 
            Math.abs(b.x - this.x) < 100 && 
            Math.abs(b.y - this.y) < 100);

        if (nearestBullet) {
            // 躲避子弹
            if (nearestBullet.x < this.x) this.x += TANK_SPEED;
            else this.x -= TANK_SPEED;
        } else {
            // 追踪玩家
            if (distance > 200) {
                this.x += dx > 0 ? TANK_SPEED : -TANK_SPEED;
                this.y += dy > 0 ? TANK_SPEED : -TANK_SPEED;
            }
        }

        // 射击AI
        if (Math.random() < 0.02) {  // 2%的概率发射子弹
            this.shoot(bullets);
        }
    }

    draw(ctx) {
        ctx.fillStyle = this.type === 'player' ? '#3498db' : '#e74c3c';
        ctx.fillRect(this.x, this.y, TANK_SIZE, TANK_SIZE);
        
        // 绘制炮管
        ctx.beginPath();
        ctx.moveTo(this.x + TANK_SIZE / 2, this.y + TANK_SIZE / 2);
        ctx.lineTo(this.x + TANK_SIZE / 2, 
                  this.type === 'player' ? this.y : this.y + TANK_SIZE);
        ctx.strokeStyle = '#fff';
        ctx.stroke();
    }
}

// 子弹类
class Bullet {
    constructor(x, y, fromPlayer) {
        this.x = x;
        this.y = y;
        this.fromPlayer = fromPlayer;
        this.active = true;
    }

    update() {
        this.y += this.fromPlayer ? -BULLET_SPEED : BULLET_SPEED;
    }

    isActive(width, height) {
        return this.active && 
               this.x >= 0 && 
               this.x <= width && 
               this.y >= 0 && 
               this.y <= height;
    }

    draw(ctx) {
        ctx.fillStyle = this.fromPlayer ? '#f1c40f' : '#e74c3c';
        ctx.fillRect(this.x - BULLET_SIZE/2, this.y - BULLET_SIZE/2, 
                    BULLET_SIZE, BULLET_SIZE);
    }
}

// 启动游戏
window.onload = () => new Game(); 